﻿using System;
using System.Linq;
using Biz.Buffer;
using Biz.EF.Platform;
using Hjt212Parser;
using log4net;

namespace Biz.Process
{
    /// <summary>
    /// 处理2011
    /// </summary>
    public static class UplineFromTgyw
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(UplineFromTgyw));

        /// <summary>
        /// 处理2011指令
        /// </summary>
        /// <param name="datatime"></param>
        /// <param name="content"></param>
        public static void Process2011(DateTime datatime, string content)
        {
            try
            {
                string mn = Parser.GetStringByKey("MN", content);
                if (string.IsNullOrWhiteSpace(mn)) return;
                var mapping = CommonInformation.GetTableMappingByGkcjMn(mn);
                if (mapping == null) return;
                string node = Parser.GetStringByKey("Node", content);
                if (string.IsNullOrWhiteSpace(node)) return;
                MasterTableOp(datatime, content, mapping, mn, node);
                HistoryTableOp(datatime, content, mapping, mn, node);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }
        }
        private static void MasterTableOp(DateTime datatime, string content, TableMapping mapping, string mn, string node)
        {
            try
            {
                using (var ctx = new PlatformContext())
                {
                    Log.Debug(content);
                    var sql = "SELECT count(*) FROM " + mapping.table_name + " where [企业基本信息ID] =" + mapping.enterprise_id;
                    var count = ctx.Database.SqlQuery<int>(sql).FirstOrDefault();
                    Log.Debug(sql + ":" + count);
                    if (count < 1)
                    {
                        sql =
                            "INSERT INTO " + mapping.table_name + " ([企业基本信息ID],[时间]) VALUES(" + mapping.enterprise_id + ",'" +
                            datatime.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                        Log.Debug(sql);
                        ctx.Database.ExecuteSqlCommand(sql);
                    }

                    sql = "SELECT count(*) FROM " + mapping.table_name + " where [企业基本信息ID] =" + mapping.enterprise_id + " and [时间]>'" + datatime.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                    count = ctx.Database.SqlQuery<int>(sql).FirstOrDefault();
                    if (count > 0) return;

                    var factors = Parser.GetPollutantExprs(content);
                    Log.Debug("Factor size:" + factors.Count);
                    Boolean isFirst = true;
                    string setCause = "";
                    foreach (var factor in factors)
                    {
                        Log.Debug("MN-Node-factor:" + mn + "-" + node + "-" + factor);
                        var field = CommonInformation.GetFieldNameByGkcjMnAndFactor(mn, node, factor);
                        Log.Debug("field:" + field);
                        if (!string.IsNullOrWhiteSpace(field))
                        {
                            if (isFirst)
                            {
                                isFirst = false;
                            }
                            else
                            {
                                setCause += ",";
                            }
                            setCause += field + "=" + (Parser.GetFloatByKey(factor, content) ?? 0);
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(setCause))
                    {
                        setCause += ",时间='" + datatime.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                        sql = "update " + mapping.table_name + " set " + setCause + " where [企业基本信息ID] =" +
                              mapping.enterprise_id;
                        Log.Debug(sql);
                        ctx.Database.ExecuteSqlCommand(sql);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }

        }
        private static void HistoryTableOp(DateTime datatime, string content, TableMapping mapping, string mn, string node)
        {
            try
            {
                var begin = new DateTime(datatime.Year, datatime.Month, datatime.Day, datatime.Hour, datatime.Minute / 10 * 10, 0);
                var end = begin.AddMinutes(10);
                using (var ctx = new PlatformContext())
                {
                    Log.Debug(content);
                    var sql = "SELECT count(*) FROM " + mapping.table_name_history + " where [企业基本信息ID] =" + mapping.enterprise_id + " and [时间]>='" + begin.ToString("yyyy-MM-dd HH:mm:ss") + "' and [时间]<'" + end.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                    var count = ctx.Database.SqlQuery<int>(sql).FirstOrDefault();
                    Log.Debug(sql + ":" + count);
                    if (count < 1)
                    {
                        sql =
                            "INSERT INTO " + mapping.table_name_history + " ([企业基本信息ID],[时间]) VALUES(" + mapping.enterprise_id + ",'" +
                            datatime.ToString("yyyy-MM-dd HH:mm:ss") + "')";
                        Log.Debug(sql);
                        ctx.Database.ExecuteSqlCommand(sql);
                    }

                    var factors = Parser.GetPollutantExprs(content);
                    Boolean isFirst = true;
                    string setCause = "";
                    foreach (var factor in factors)
                    {
                        var field = CommonInformation.GetFieldNameByGkcjMnAndFactor(mn, node, factor);
                        if (!string.IsNullOrWhiteSpace(field))
                        {
                            if (isFirst)
                            {
                                isFirst = false;
                            }
                            else
                            {
                                setCause += ",";
                            }
                            setCause += field + "=" + (Parser.GetFloatByKey(factor, content) ?? 0);
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(setCause))
                    {
                        sql = "update " + mapping.table_name_history + " set " + setCause + " where [企业基本信息ID] =" +
                              mapping.enterprise_id + " and [时间]>='" + begin.ToString("yyyy-MM-dd HH:mm:ss") +
                              "' and [时间]<'" + end.ToString("yyyy-MM-dd HH:mm:ss") + "'";
                        Log.Debug(sql);
                        ctx.Database.ExecuteSqlCommand(sql);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }

        }
    }
}
